package org.jumiz.javafx.client.pages.commonents;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import javafx.event.ActionEvent;
import javafx.event.EventType;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import lombok.Data;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jumiz.javafx.client.pages.user.bean.UserEntity;
import org.jumiz.javafx.client.util.FileUtil;
import org.jumiz.javafx.client.util.SwitchScene;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class CrudTablePane<E> extends FlowPane {

    private static Logger logger = LogManager.getLogger(CrudTablePane.class);

    public CrudTablePane(String configPath) {
        super();
        String json = FileUtil.loadJson(configPath);
        Config config = JSON.parseObject(json, Config.class);
        this.init(config);
    }

    public CrudTablePane(Config config) {
        super();
        this.init(config);
    }

    private void init(Config config) {
        HBox buttonGroup = new HBox(5);
        List<Button> buttonList = config.getButtonGroup().stream().map(item -> {
            Button button = new Button(item.getButton());
            button.getStyleClass().addAll("btn", "btn-" + item.getType());
            button.setOnMouseClicked(event -> {
                DialogPane dialogPane = new DialogPane();
                dialogPane.getStylesheets().add(FileUtil.loadCss("static/css/style.css").toExternalForm());

                FormPane formPane = new FormPane();
                List<TableConfig> columns = config.getEditConfig().getColumns();
                for (int i = 0; i < columns.size(); i++) {
                    TableConfig fieldConfig = columns.get(i);
                    formPane.addControl(fieldConfig, FormPane.ControlType.TextField);
                }
//                dialogPane.setContentText("content");
                dialogPane.setContent(formPane);
//                dialogPane.setGraphic(null);
                javafx.scene.control.ButtonType saveButton = new javafx.scene.control.ButtonType("保存", ButtonBar.ButtonData.YES);
                dialogPane.getButtonTypes().addAll(saveButton, javafx.scene.control.ButtonType.CANCEL);

                Dialog<Object> dialog = new Dialog<>();
                dialog.setDialogPane(dialogPane);
                dialog.setTitle(item.getButton());

                dialog.getDialogPane().lookupButton(saveButton).addEventFilter(ActionEvent.ACTION, saveEvent -> {
                    Valid valid = formPane.valid(config.getEditConfig().rules);
                    if (valid.isValid()) {
                        logger.debug("验证通过：" + JSON.toJSONString(formPane.getFormData()));
                        return;
                    }
                    logger.debug(JSON.toJSONString(valid));
                    saveEvent.consume();
                });
                dialog.show();
            });
            return button;
        }).collect(Collectors.toList());
        buttonGroup.getChildren().addAll(buttonList);
        buttonGroup.setPadding(new Insets(0, 0, 5, 0));

        TableView<E> tableView = new TableView<>();
        tableView.setPrefWidth(SwitchScene.defaultWidth() - 220);
        List<TableColumn<E, String>> columnList = config.getTableConfig().stream().map(item -> {
            TableColumn<E, String> column = new TableColumn<>(item.getLabel());
            column.setCellValueFactory(new PropertyValueFactory<>(item.getField()));
            column.setVisible(item.isVisible());
            return column;
        }).collect(Collectors.toList());
        tableView.getColumns().addAll(columnList);
        tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        this.setPadding(new Insets(5));
        this.getChildren().addAll(buttonGroup, tableView);
    }

    @Data
    public static class TableConfig {
        private String field;
        private String label;
        private String type;
        private boolean visible;
    }

    @Data
    public static class ButtonGroup {
        private String button;
        private ButtonType type;
    }

    public enum ButtonType {
        primary,
        danger,
        warning,
        info,
        success;
    }

    @Data
    public static class EditConfig {
        private String primaryKey;
        private List<TableConfig> columns;
        private List<Rule> rules;
    }

    @Data
    public static class Rule {
        private String field;
        private Boolean required;
    }

    @Data
    public static class Valid {
        private boolean valid;
        private String errMesg;
    }

    @Data
    public static class Config {
        private List<ButtonGroup> buttonGroup;
        private List<TableConfig> tableConfig;
        private EditConfig editConfig;
    }

}
